package com.myersinfosys.protrack.poi;

import java.io.File;

// main POI reader class
public class PoiExcelRead {

    public static void main(String[] args) throws Exception {
    	final Boolean isTest = false;
    	String xlsfilename = ".//data//data.xlsx";
    	String outfilebase = ".//data//test";
		String tablename = "mytable";
    	int maxSheetRead = 1;
    	Boolean readFirstSheetOnly = false;
    	Boolean combineSheets = true;

    	
		if (!isTest && args.length >= 3) {
		   xlsfilename = args[0];
		   outfilebase = args[1];
		   tablename = args[2];
		   
		   readFirstSheetOnly = (args.length == 4) ? (args[3].equals("1")) : true;
		   combineSheets = (args.length == 4) ? (args[3].equals("-1")) : false;
		}
      
		if (xlsfilename.length() > 0 && outfilebase.length() > 0) { 
			
			XLSReader xls = new XLSReader(xlsfilename, readFirstSheetOnly, combineSheets);
			
			maxSheetRead = xls.getNSheets();
			if(readFirstSheetOnly)
				maxSheetRead = 1;
			if(maxSheetRead > 99)
				maxSheetRead = 99;					
			
			for(int s=0; s<maxSheetRead; s++) {
				
				if(xls.readData(s)) {
					if(readFirstSheetOnly)
						xls.writeUnlData(outfilebase + ".unl");
					else
						xls.writeUnlData(outfilebase + String.format("%02d", s+1) + ".unl");
					
					if(tablename.length() > 0) {
						if(s==0) {
							File f = new File(outfilebase + ".sql");
							if(f.exists())
								f.delete();
						}
							
						xls.writeSqlCreate(xls.makeValidTableName(tablename), outfilebase + ".sql");
					}	
				} else {
					System.out.println("No data, or file cannot be read.");
				}
			}
		} else {
			System.out.println("Usage:");
			System.out.println("java PoiExcelRead xlsfilename outfilebase tablename sheetoption");
			System.out.println("Ex: java PoiExcelRead /tmp/data.xls /tmp/test mytable");
			System.out.println("note: if tablename is empty, the .sql file is not created.");
		}
    		
    }
}

